import { useState, useCallback } from 'react'
import { PuzzlePieceIcon, PlayIcon, ArrowPathIcon } from '@heroicons/react/24/outline'
import { useAuthStore } from '@/stores/authStore'

type Player = 'black' | 'white'
type CellValue = Player | null
type Board = CellValue[][]

const BOARD_SIZE = 15
const WINNING_LENGTH = 5

const GamePage = () => {
  const { user } = useAuthStore()
  const [board, setBoard] = useState<Board>(() => 
    Array(BOARD_SIZE).fill(null).map(() => Array(BOARD_SIZE).fill(null))
  )
  const [currentPlayer, setCurrentPlayer] = useState<Player>('black')
  const [winner, setWinner] = useState<Player | 'draw' | null>(null)
  const [gameStarted, setGameStarted] = useState(false)
  const [playerColor, setPlayerColor] = useState<Player>('black')
  const [scores, setScores] = useState({ black: 0, white: 0, draw: 0 })

  const checkWinner = useCallback((board: Board, row: number, col: number, player: Player): boolean => {
    const directions = [
      [0, 1],   // 水平
      [1, 0],   // 垂直
      [1, 1],   // 对角线
      [1, -1],  // 反对角线
    ]

    for (const [dx, dy] of directions) {
      let count = 1
      
      // 向一个方向检查
      for (let i = 1; i < WINNING_LENGTH; i++) {
        const newRow = row + dx * i
        const newCol = col + dy * i
        if (
          newRow >= 0 && newRow < BOARD_SIZE &&
          newCol >= 0 && newCol < BOARD_SIZE &&
          board[newRow][newCol] === player
        ) {
          count++
        } else {
          break
        }
      }
      
      // 向相反方向检查
      for (let i = 1; i < WINNING_LENGTH; i++) {
        const newRow = row - dx * i
        const newCol = col - dy * i
        if (
          newRow >= 0 && newRow < BOARD_SIZE &&
          newCol >= 0 && newCol < BOARD_SIZE &&
          board[newRow][newCol] === player
        ) {
          count++
        } else {
          break
        }
      }
      
      if (count >= WINNING_LENGTH) {
        return true
      }
    }
    
    return false
  }, [])

  const handleCellClick = (row: number, col: number) => {
    if (!gameStarted || board[row][col] || winner) return
    
    // 只允许玩家在自己的回合下棋
    if (currentPlayer !== playerColor) return

    const newBoard = board.map(r => [...r])
    newBoard[row][col] = currentPlayer
    setBoard(newBoard)

    if (checkWinner(newBoard, row, col, currentPlayer)) {
      setWinner(currentPlayer)
      setScores(prev => ({
        ...prev,
        [currentPlayer]: prev[currentPlayer] + 1
      }))
    } else {
      // 切换玩家
      const nextPlayer = currentPlayer === 'black' ? 'white' : 'black'
      setCurrentPlayer(nextPlayer)
      
      // 模拟AI对手
      if (nextPlayer !== playerColor) {
        setTimeout(() => {
          makeAIMove(newBoard, nextPlayer)
        }, 1000)
      }
    }
  }

  const makeAIMove = (currentBoard: Board, aiPlayer: Player) => {
    // 简单的AI逻辑：随机选择空位
    const emptyCells: [number, number][] = []
    for (let i = 0; i < BOARD_SIZE; i++) {
      for (let j = 0; j < BOARD_SIZE; j++) {
        if (!currentBoard[i][j]) {
          emptyCells.push([i, j])
        }
      }
    }

    if (emptyCells.length === 0) {
      setWinner('draw')
      setScores(prev => ({ ...prev, draw: prev.draw + 1 }))
      return
    }

    const [aiRow, aiCol] = emptyCells[Math.floor(Math.random() * emptyCells.length)]
    const newBoard = currentBoard.map(r => [...r])
    newBoard[aiRow][aiCol] = aiPlayer
    setBoard(newBoard)

    if (checkWinner(newBoard, aiRow, aiCol, aiPlayer)) {
      setWinner(aiPlayer)
      setScores(prev => ({
        ...prev,
        [aiPlayer]: prev[aiPlayer] + 1
      }))
    } else {
      setCurrentPlayer(playerColor)
    }
  }

  const startGame = (color: Player) => {
    setPlayerColor(color)
    setGameStarted(true)
    setCurrentPlayer('black')
    
    // 如果玩家选择白棋，AI先手
    if (color === 'white') {
      setTimeout(() => {
        makeAIMove(board, 'black')
      }, 500)
    }
  }

  const resetGame = () => {
    setBoard(Array(BOARD_SIZE).fill(null).map(() => Array(BOARD_SIZE).fill(null)))
    setCurrentPlayer('black')
    setWinner(null)
    setGameStarted(false)
  }

  const getCellContent = (value: CellValue) => {
    if (!value) return null
    return (
      <div className={`w-6 h-6 rounded-full ${
        value === 'black' ? 'bg-gray-900' : 'bg-white border-2 border-gray-300'
      }`} />
    )
  }

  const getPlayerName = (player: Player) => {
    if (player === playerColor) {
      return user?.displayName || user?.username || '你'
    }
    return 'AI'
  }

  return (
    <div className="space-y-6">
      {/* 页面头部 */}
      <div className="text-center">
        <h1 className="text-2xl font-bold text-gray-900 mb-2">五子棋游戏</h1>
        <p className="text-gray-600">
          和AI来一局五子棋吧！先连成五子者获胜 🎮
        </p>
      </div>

      {/* 游戏状态 */}
      <div className="flex items-center justify-center space-x-8">
        <div className="text-center">
          <div className="flex items-center justify-center space-x-2 mb-2">
            <div className="w-4 h-4 bg-gray-900 rounded-full"></div>
            <span className="font-medium">黑棋</span>
          </div>
          <p className="text-2xl font-bold text-gray-900">{scores.black}</p>
        </div>
        
        <div className="text-center">
          <p className="text-sm text-gray-600 mb-2">平局</p>
          <p className="text-2xl font-bold text-gray-900">{scores.draw}</p>
        </div>
        
        <div className="text-center">
          <div className="flex items-center justify-center space-x-2 mb-2">
            <div className="w-4 h-4 bg-white border-2 border-gray-300 rounded-full"></div>
            <span className="font-medium">白棋</span>
          </div>
          <p className="text-2xl font-bold text-gray-900">{scores.white}</p>
        </div>
      </div>

      {/* 游戏控制 */}
      {!gameStarted ? (
        <div className="text-center space-y-4">
          <p className="text-gray-600">选择你的棋子颜色开始游戏</p>
          <div className="flex justify-center space-x-4">
            <button
              onClick={() => startGame('black')}
              className="flex items-center space-x-2 px-6 py-3 bg-gray-900 text-white rounded-lg hover:bg-gray-800 transition-colors"
            >
              <div className="w-4 h-4 bg-white rounded-full"></div>
              <span>执黑棋</span>
            </button>
            <button
              onClick={() => startGame('white')}
              className="flex items-center space-x-2 px-6 py-3 bg-white text-gray-900 border-2 border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
            >
              <div className="w-4 h-4 bg-gray-900 rounded-full"></div>
              <span>执白棋</span>
            </button>
          </div>
        </div>
      ) : (
        <div className="text-center space-y-4">
          {winner ? (
            <div className="space-y-4">
              <div className={`text-xl font-bold ${
                winner === 'draw' ? 'text-gray-600' : 
                winner === playerColor ? 'text-green-600' : 'text-red-600'
              }`}>
                {winner === 'draw' ? '平局！' : 
                 winner === playerColor ? '你赢了！🎉' : 'AI获胜！'}
              </div>
              <button
                onClick={resetGame}
                className="btn-primary flex items-center gap-2 mx-auto"
              >
                <ArrowPathIcon className="h-5 w-5" />
                再来一局
              </button>
            </div>
          ) : (
            <div className="space-y-2">
              <p className="text-lg font-medium">
                当前回合: {getPlayerName(currentPlayer)}
              </p>
              <div className="flex items-center justify-center space-x-2">
                <div className={`w-4 h-4 rounded-full ${
                  currentPlayer === 'black' ? 'bg-gray-900' : 'bg-white border-2 border-gray-300'
                }`}></div>
                <span className="text-sm text-gray-600">
                  {currentPlayer === playerColor ? '你的回合' : 'AI思考中...'}
                </span>
              </div>
              <button
                onClick={resetGame}
                className="text-sm text-gray-500 hover:text-gray-700 transition-colors"
              >
                重新开始
              </button>
            </div>
          )}
        </div>
      )}

      {/* 游戏棋盘 */}
      <div className="flex justify-center">
        <div className="inline-block p-4 bg-yellow-100 rounded-lg">
          <div className="grid grid-cols-15 gap-0 bg-yellow-200 p-2 rounded" style={{
            gridTemplateColumns: `repeat(${BOARD_SIZE}, minmax(0, 1fr))`
          }}>
            {board.map((row, rowIndex) =>
              row.map((cell, colIndex) => (
                <button
                  key={`${rowIndex}-${colIndex}`}
                  onClick={() => handleCellClick(rowIndex, colIndex)}
                  className={`w-8 h-8 border border-gray-800 flex items-center justify-center hover:bg-yellow-300 transition-colors ${
                    !gameStarted || winner ? 'cursor-not-allowed' : 'cursor-pointer'
                  }`}
                  disabled={!gameStarted || !!winner || currentPlayer !== playerColor}
                >
                  {getCellContent(cell)}
                </button>
              ))
            )}
          </div>
        </div>
      </div>

      {/* 游戏说明 */}
      <div className="card p-6">
        <h3 className="text-lg font-semibold text-gray-900 mb-3">游戏规则</h3>
        <ul className="space-y-2 text-sm text-gray-600">
          <li>• 在15×15的棋盘上进行游戏</li>
          <li>• 黑棋先手，白棋后手</li>
          <li>• 率先在横、竖、斜任意方向连成5子者获胜</li>
          <li>• 点击空白格子放置棋子</li>
          <li>• 你可以选择执黑棋或白棋与AI对战</li>
        </ul>
      </div>
    </div>
  )
}

export default GamePage